<?php

namespace App\Http\Controllers\others;

use App\models\UploadFile;
use File;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Storage;
use Image;

class UploadFileController extends Controller{

    public function imageUpload(Request $request){
        $array = array(
            'id'  => 1,
            'url' => self::getImgPateh($request, 'file')
        );
        return $array;
    }

    public function imgUpload(Request $request){
        $array = array(
            'filename' => cdn(self::getImgPateh($request, 'file'))
        );
        return $array;
    }

    protected static function isImg($ex){
        if (strcasecmp($ex, 'png') == 0 ||
            strcasecmp($ex, 'jpg') == 0 ||
            strcasecmp($ex, 'gif') == 0 ||
            strcasecmp($ex, 'jpeg') == 0 ||
            strcasecmp($ex, 'bmp') == 0){
            return true;
        }
        return false;
    }

    /**
     * 图片设置
     *
     * @param Request $request
     * @param $na
     * @param array|null $info
     * @return int|string
     */
    public static function getImgPateh(Request $request, $na, array $info = null){
        $file = $request->file($na);
        if (!$file->isValid()){
            return -1;
        }
        if (self::isImg($file->getClientOriginalExtension()) == false){
            return -1;
        }
        $md5file = md5_file($file);
        $fileMod = UploadFile::getFilesByMd5($md5file);
        if (!empty($fileMod)){
            return '/file/'.$fileMod->md5;
        }
        $fileMod                = new UploadFile();
        $fileMod->md5           = $md5file;
        $fileMod->filename      = $file->getClientOriginalName();
        $fileMod->size          = $file->getSize();
        $fileMod->extension     = $file->getClientOriginalExtension();
        $date = date('Ymd');
        $newName = $fileMod->md5.'.'.$fileMod->extension;
        $path = '/files/'.$fileMod->extension.'/'.$date."/".$newName;
        Storage::disk('public')->put($path, File::get($file->getPathname()));
        $fileMod->path          = $path;
        $fileMod->save();
        return '/file/'.$fileMod->md5;
    }

    public function getFile($md5, Request $request){
        $file = UploadFile::where('md5', $md5)->first();
        if (empty($file) || Storage::disk('public')->has($file->path) == false){
            $contents = Storage::disk('public')->get('no.jpg');
        }else{
            $contents = Storage::disk('public')->get($file->path);
        }
        $type = $request->get('type');
        $img = Image::make($contents);
        if (!empty($type)){
            if ($type == 'avatar'){
                $img->resize(300, 300);
            }
        }
        if ($request->has('w') && is_numeric($request->get('w')) && $request->has('h') && is_numeric($request->get('h'))){
            $img->resize($request->get('w'), $request->get('h'));
        }
        return $img->response();
    }
}
